package com.uinnova.product.eam.init;

import com.uinnova.project.base.diagram.util.RedisUtil;
import com.uino.bean.permission.base.SysUser;
import com.uino.util.sys.CurrentUserGetter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 太保获取当前用户方法
 *
 * @author lichong
 */
@Component
@Slf4j
@ConditionalOnProperty(prefix = "monet.login", name = "loginMethod", havingValue = "taibao")
public class TaibaoCurrentUser implements CurrentUserGetter {

    @Autowired
    private RedisUtil redisUtil;

    public static final String taibaiUserProfile = "EA:TAIBAI:USER:";

    /**
     * 获取当前用户的登录信息
     *
     * @return
     */
    @Override
    public SysUser getCurrentUserInfo() {
        String currentToken = getCurrentToken();
        return getCurrentUserInfo(currentToken);
    }

    @Override
    public SysUser getCurrentUserInfo(String currentToken) {
        if (currentToken == null) {
            return null;
        }
        Object userObj = redisUtil.get(currentToken);
        log.debug("taibao-getCurrentUserInfo:{}", userObj);
        if (userObj != null) {
            return (SysUser) userObj;
        } else {
            return null;
        }
    }

    @Override
    public String getCurrentToken() {
        //已校验的用户无需再次校验
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attrs==null){
            return null;
        }
        HttpServletRequest request;
        String ticket;
        request = attrs.getRequest();
        Object taibaoTicket = request.getAttribute("taibaoTicket");
        log.debug("taibao-getCurrentToken:{}", taibaoTicket);
        if (taibaoTicket != null) {
            ticket = taibaiUserProfile + taibaoTicket;
        } else {
            return null;
        }
        return ticket;
    }
}


